<template>
  <div class="container">
    <el-form :model="searchForm" class="search-form" ref="searchForm" label-width="0">
      <el-row>
        <el-col :span="4">
          <el-form-item>
            <el-input v-model.trim="searchForm.nameOrPhone" placeholder="姓名" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select clearable placeholder="审核状态" v-model="searchForm.auditStatus">
              <el-option label="等待审核" value="0"></el-option>
              <el-option label="审核通过" value="1"></el-option>
              <el-option label="审核未通过" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-select clearable placeholder="照片审核状态" v-model="searchForm.photoAuditStatus">
              <el-option label="等待审核" value="0"></el-option>
              <el-option label="审核通过" value="1"></el-option>
              <el-option label="审核未通过" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-date-picker clearable value-format="yyyy-MM-dd" v-model="searchForm.createTime" type="date"
              placeholder="创建日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="btn-col">
          <div class="buttons">
            <el-button type="primary" @click="queryInPage(1)">查询
            </el-button>
            <el-button type="primary" @click="resetAll">重置
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <el-radio-group v-model="searchForm.peopleType" @change="queryInPage(1)">
        <el-radio-button :label="0">
          全部
        </el-radio-button>
        <el-radio-button :label="item.val" v-for="(item,index) in getPeopletypelist" :key="'getPeopletypelist'+index">
          {{item.name}}
        </el-radio-button>
        <el-radio-button :label="9">
          其他
        </el-radio-button>
      </el-radio-group>
    </div>
    <div class="batch-action">
      <el-button type="primary" @click="approveAction(1)">审核简历</el-button>
      <el-button type="primary" @click="approveAction(2)">审核照片</el-button>
      <el-button type="primary" @click="refreshReumeAction">刷新</el-button>
      <el-button type="primary" @click="deleteAction">删除</el-button>
      <el-button type="primary" @click="changeVisible">重置密码</el-button>
    </div>

    <el-table :row-key="getRowKeys" v-loading="tableLoading" ref="multipleTable"
      @selection-change="handleSelectionChange" :data="tableData">
      <el-table-column :reserve-selection="true" type="selection" fixed="left" width="55">
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="200">
        <template slot-scope="scope">
          <div class="name-box">
            <div class="name-style">
              <span class="type" v-if="scope.row.peopleTypeText">[{{scope.row.peopleTypeText}}]</span>
              <!-- <span class="type">[高校毕业生]</span> -->
              {{scope.row.name}}
            </div>
            <el-button type="text" @click="showImg(scope.row.photo)" v-if="scope.row.photo">照片
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号码" align="center">
      </el-table-column>
      <el-table-column prop="integrity" label="完整指数" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.integrity">{{scope.row.integrity}}%</span>
        </template>
      </el-table-column>
      <el-table-column prop="auditStatus" label="审核状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.auditStatus == 0">待审核</span>
          <span v-if="scope.row.auditStatus == 1" class="success">通过</span>
          <span v-if="scope.row.auditStatus == 2" class="reject">未通过</span>
        </template>
      </el-table-column>
      <el-table-column prop="photoAuditStatus" label="照片审核状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.photoAuditStatus == 0">待审核</span>
          <span v-if="scope.row.photoAuditStatus == 1" class="success">通过</span>
          <span v-if="scope.row.photoAuditStatus == 2" class="reject">未通过</span>
        </template>
      </el-table-column>
      <el-table-column prop="publicity" label="公开" align="center">
        <template slot-scope="scope">
          {{scope.row.publicity == 1 ? '对所有公开' : '完全保密'}}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
      </el-table-column>
      <el-table-column prop="refreshTime" label="刷新时间" align="center">
        <template slot-scope="scope">
          {{scope.row.refreshTime ? scope.row.refreshTime : '-'}}
        </template>
      </el-table-column>
      <el-table-column prop="msgcount" label="短信推送次数" align="center">
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="250px">
        <template slot-scope="scope">
          <el-button type="text" @click="handleClick(scope.row)">日志</el-button>
          <el-button type="text" @click="goDetail(scope.row)">查看</el-button>
          <el-button type="text" @click="changeVisible(scope.row)">重置密码</el-button>
          <el-button type="text" @click="loginPerson(scope.row)">管理</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination class="center" background @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="searchForm.page" :page-sizes="[10,30,60, 100, 200, 300]" :page-size="searchForm.size"
      layout="prev, pager, next, jumper, sizes, total" :total="totalNum"></el-pagination>

    <el-dialog @close="clearValid" :visible.sync="approveShow" center :title="type == 1 ? '审核简历' : '审核照片'"
      width="610px">
      <el-form :model="approveForm" label-width="134px" label-position="left" ref="approveForm" :rules="rules">
        <el-form-item label="审核结果：" prop="status">
          <el-radio-group v-model="approveForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
            <el-radio :label="0">待定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核不通过原因：" v-if="approveForm.status == 2" prop="content">
          <el-input placeholder="请输入审核不通过原因" type="textarea" v-model="approveForm.content" :rows="8"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="approveShow = false">取 消</el-button>
        <el-button type="primary" @click="submitApprove">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="重置密码" :visible.sync="passwordVisible" width="500px" class="resetPassword"
      :before-close="handleClose">
      <el-form ref="passwordForm" :model='passwordForm' :rules='rules'>
        <el-form-item prop="password">
          <el-input placeholder="密码" v-model="passwordForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input placeholder="确认密码" v-model="passwordForm.repassword" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPassword">确 定</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <viewer :images="temImg" v-show="false">
      <img :src="temImg[0]" width="1" id="img">
    </viewer>
  </div>
</template>

<script>
import { resumeList, deleteResume, refreshResume, auditPhoto, auditResume, resetPassword, getPsToken, getPeopletype } from '../../../api/personal';
import { encrypt } from '../../../utils/unitFile'
import bus from '../../common/bus'
export default {
  name: 'resumeList',
  data () {
    var validateComfirmPwd = (rule, value, callback) => {
      console.log(this.passwordForm.password, value);
      if (this.passwordForm.password != value) {
        callback(new Error('确认密码与密码不一致！'));
      } else {
        callback();
      }
    };
    return {
      ids: null,
      userIds: null,
      passwordVisible: false,
      category: '',
      passwordForm: {
        ids: '',
        password: '',
        repassword: ''
      },
      rules: {
        status: [
          { required: true, message: '请选择审批结果', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入审核不通过原因', trigger: 'blur' }
        ],
        repassword: [{ required: true, message: '请输入确认密码', trigger: 'change' }, { validator: validateComfirmPwd }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^[0-9a-zA-Z_]{6,20}$/, message: '密码由长度为6-20的数字、字母或下划线组成' }
        ]
      },
      temImg: [],
      approveForm: {
        status: null,
        content: ''
      },
      type: 1, // 1简历，2照片
      approveShow: false,
      totalNum: 0,
      tableLoading: false,
      selectArr: [],
      tableData: [],
      checked: false,
      searchForm: {
        page: 1,
        size: 10,
        nameOrPhone: '',
        auditStatus: '',
        photoAuditStatus: '',
        createTime: null,
        peopleType: 0
      },
      approveOptions: [],
      pictureOptions: [],
      getPeopletypelist: []
    }
  },
  created () {
    this.url = process.env.VUE_APP_URL || '';
    if (this.$route.query.auditStatus == 0 || this.$route.query.photoAuditStatus == 0) {
      this.searchForm.auditStatus = this.$route.query.auditStatus || ''
      this.searchForm.photoAuditStatus = this.$route.query.photoAuditStatus || ''
    }
    this.queryInPage();
    this.getPeopletype()
  },
  watch: {
    '$route.fullPath': function (val, oldVal) {
      this.$nextTick(() => {
        if (this.$route.query.auditStatus == 0 || this.$route.query.photoAuditStatus == 0) {
          this.searchForm.auditStatus = this.$route.query.auditStatus || ''
          this.searchForm.photoAuditStatus = this.$route.query.photoAuditStatus || ''
          this.queryInPage();
        }
      })
    }
  },
  methods: {
    showImg (url) {
      this.temImg = [];
      this.temImg.push(url)
      document.getElementById("img").click();
    },
    getRowKeys (row) {
      return row.id;
    },
    toggleSelection (val) {
      val && this.$refs.multipleTable.toggleAllSelection()
      !val && this.$refs.multipleTable.clearSelection()
    },
    handleSelectionChange (val) {
      this.selectArr = val || [];
      let temp = [];
      temp = this.selectArr.map(v => {
        return v.id;
      })
      this.userIds = this.selectArr.map(i => {
        return i.userId
      })
      this.ids = temp.join(',');
      // this.checked = (val.length === this.tableData.length) ? true : false
    },
    handleClick (row) {
      /**
    * opeType 个人用户 1   企业用户 2   管理员用户 3 why 不知道 问后台
    */
      this.$router.push({ path: '/log', query: { userName: row.userName, opeType: 1 } });
    },
    queryInPage (page) {
      this.tableLoading = true;
      page ? this.searchForm.page = page : '';
      resumeList(this.searchForm).then(data => {
        if (data.success) {
          this.tableData = data.data.records || [];
          this.totalNum = data.data.total || 0;
          this.$refs.multipleTable.clearSelection()
        } else {
          this.$message.error(`${data.msg}`);
        }
        this.tableLoading = false;
      });
    },
    //获取人员类别
    getPeopletype (page) {

      getPeopletype(this.searchForm).then(data => {
        if (data.success) {
          this.getPeopletypelist = data.data.people_type
          console.log(this.getPeopletypelist, 'this.getPeopletypelist')
        } else {

        }

      });
    },
    // 弹出修改密码窗口
    changeVisible (row) {
      if (row.userId || this.selectArr.length) {
        this.passwordVisible = true;
        if (row.userId) {
          this.passwordForm.ids = row.userId;
        } else {
          this.passwordForm.ids = this.selectArr.map(item => {
            return item.userId
          }).join(',')
          console.log(this.passwordForm.ids);

        }
      } else {
        this.$message.error(`请选择需要修改密码的公司!`)
      }
    },
    handleClose () {
      this.$refs.passwordForm.resetFields();
      this.passwordVisible = false;
    },
    // 修改密码
    resetPassword (row) {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          let query = {
            ids: this.passwordForm.ids,
            password: encrypt(this.passwordForm.password),
            repassword: encrypt(this.passwordForm.repassword),
            accountType: 1
          }
          resetPassword(query).then(data => {
            if (data.success) {
              this.$message.success('重置密码成功');
              this.handleClose()
            } else {
              this.$message.error(`${data.msg}`);
              this.handleClose()
            }
          })
        }
      });
    },
    resetAll () {
      this.searchForm = {
        page: 1,
        size: 10,
        nameOrPhone: '',
        auditStatus: '',
        photoAuditStatus: '',
        createTime: null,
      };
      this.$refs.multipleTable.clearSelection();
      this.queryInPage();
    },

    handleSizeChange (val) {
      this.searchForm.size = val;
      this.queryInPage();
    },

    handleCurrentChange (val) {
      this.searchForm.page = val;
      this.queryInPage();
    },
    goDetail (row) {
      bus.$emit('openTags', { fullPath: `/resumeDetail?id=${row.id}`, meta: { title: row.name } })

      // this.$router.push({
      //   path: '/resumeDetail',
      //   query: {
      //     id: id
      //   }
      // })
    },
    // 去个人中心登录个人
    loginPerson (row) {
      getPsToken(row.userId).then(res => {
        if (res.success) {
          localStorage.setItem('ps_Authorization', res.data.token)
          localStorage.setItem('ps_userName', res.data.userName)
          localStorage.setItem('ps_userId', res.data.userId)
          // window.location.href = 'https://www.baidu.com'
          // window.open('https://www.baidu.com', '_blank');
          window.open(this.url + '/person', '_blank');
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    submitApprove () {
      this.$refs['approveForm'].validate((valid) => {
        let query = { ...this.approveForm, ids: this.ids.split(','), userIds: this.userIds }
        if (valid) {
          if (this.type == 1) {
            auditResume(query).then(data => {
              if (data.success) {
                this.$notify({
                  type: "success",
                  message: "审核成功"
                });
                this.approveShow = false;
                this.queryInPage();
              } else {
                this.$message.error(`${data.msg}`);
              }
            });
          } else {
            auditPhoto(query).then(data => {
              if (data.success) {
                this.$notify({
                  type: "success",
                  message: "审核成功"
                });
                this.approveShow = false;
                this.queryInPage();
              } else {
                this.$message.error(`${data.msg}`);
              }
            });
          }

        } else {
          return false;
        }
      });
    },

    approveAction (type) {
      this.type = type;
      if (!this.selectArr.length) {
        let msg = type == 1 ? '请选择要审核的简历' : '请选择要审核的照片';
        this.$message(msg);
      } else {
        this.approveForm = {
          status: null,
          content: ''
        },
          this.approveShow = true;
      }
    },

    deleteAction () {
      if (!this.selectArr.length) {
        this.$message('请选择要删除的简历');
      } else {
        this.$confirm('确定删除选中的简历吗？', '删除简历', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteResume(this.ids).then(data => {
            if (data.success) {
              this.$notify({
                type: "success",
                message: "删除成功"
              });
              this.queryInPage();
            } else {
              this.$message.error(`${data.msg}`);
            }
          });
        })

      }
    },
    refreshReumeAction () {
      if (!this.selectArr.length) {
        this.$message('请选择要刷新的简历');
      } else {
        this.$confirm('确定刷新选中的简历吗？', '刷新简历', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          refreshResume(this.ids).then(data => {
            if (data.success) {
              this.$notify({
                type: "success",
                message: "刷新成功"
              });
              this.queryInPage();
            } else {
              this.$message.error(`${data.msg}`);
            }
          });
        })

      }
    },
    clearValid () {
      this.$refs['approveForm'].resetFields();
    },
    deleteResume () {

    }
  },
}
</script>
<style scoped>
.reject {
    color: #dd6161;
}

.success {
    color: #67c23a;
}

.search-form .el-form-item {
    margin-right: 10px;
}
.search-form .el-input {
    max-width: 215px;
}
.half-select .el-checkbox__inner {
    background-color: #ffcf10;
}

span.el-checkbox__inner::before {
    content: '';
    position: absolute;
    display: block;
    background-color: #fff;
    height: 2px;
    -webkit-transform: scale(0.5);
    transform: scale(0.5);
    left: 0;
    right: 0;
    top: 5px;
}
.batch-action {
    margin-bottom: 20px;
}
.el-table /deep/ td {
    text-align: center;
}
.el-table /deep/ th {
    text-align: center;
}
.batch-action .el-checkbox {
    margin-right: 20px;
}

.batch-action .el-button--small {
    min-width: 80px;
}

.center {
    text-align: center;
    margin-top: 20px;
}

.el-message-box__title {
    font-size: 14px;
}
.name-box {
    text-align: left;
}
.name-box .name-style {
    display: inline-block;
    max-width: calc(100% - 25px);
    text-align: left !important;
    font-size: 14px;
    vertical-align: top;
}

.name-box .el-button--text {
    display: inline-block;
    width: 20px;
    vertical-align: top;
    padding: 4px 0;
    margin-left: 5px;
}

.btn-col {
    text-align: right;
}
.resetPassword .el-form-item {
    text-align: center;
}
.resetPassword .el-form .el-form-item .el-button {
    margin: 0 10px;
    width: 120px;
    height: 40px;
}
.resetPassword /deep/ .el-input {
    width: 100%;
}
.resetPassword /deep/ .el-input__inner {
    height: 40px;
    width: 100%;
}
.resetPassword .el-dialog .el-form .el-form-item .el-form-item__content /deep/ .el-form-item__error {
    left: 0 !important;
}
.type {
    margin-right: 4px;
    font-size: 10px !important;
    color: rgb(109, 180, 52);
}
.container /deep/ .el-radio-button__inner {
    background: #ebf7ff;
    color: #1893fc;
    margin-right: 10px;
    border-left: 1px solid #dcdfe6;
    margin-bottom: 15px;
}
.container /deep/ .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
    -webkit-box-shadow: -1px 0 0 0 #409eff;
    box-shadow: -1px 0 0 0 #409eff;
}
</style>